﻿using System;
using System.IO;
using Foothill.Common;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service;
using Foothill.Service.AdService;
using Foothill.Service.Session;
using Foothill.Web.EditPost.App_LocalResources;

namespace Foothill.Web
{
    public partial class EditPostCodeBehind : FoothillBasePage
    {
        private IAdService _adService;
        private ISessionService _sessionService;
        private IPostValidator _postValidator;
        
        private int PostId
        {
            get
            {
                object obj = ViewState["PostId"];
                int id = (obj == null) ? 0 : (int)obj;
                return id;
            }
            set
            {
                ViewState["PostId"] = value;
            }
        }

        private int _maskedPostId;
        private string _editKey;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            _adService = IocContainer.GetInstance<IAdService>();
            _sessionService = IocContainer.GetInstance<ISessionService>();
            _postValidator = IocContainer.GetInstance<IPostValidator>();
            
            if (!IsPostBack)
            {
                ForSaleAd postToEdit;
                
                // authenticate
                if (Authenticate(out postToEdit))
                {
                    DisplayPostDetails(postToEdit);

                    SetupUpdateControls(postToEdit);
                }
                else
                {
                    // display can not authenticate error
                    DisplayCanNotAuthenticatePage();
                }
            }
        }

        private void SetupUpdateControls(ForSaleAd postToEdit)
        {
            AdStatusLookup status = _adService.DetermineAdStatus(postToEdit);

            switch (status)
            {
                case AdStatusLookup.Active:
                    lblUpdateHistory.Visible = false;
                    btnTakeOffline.Visible = true;
                    pnlUpdate.Visible = true;
                break;
                case AdStatusLookup.Expired:
                    lblUpdateHistory.Visible = true;
                    btnTakeOffline.Visible = false;
                    pnlUpdate.Visible = false;

                    lblUpdateHistory.Text = "此广告已过期";
                    break;
                case AdStatusLookup.Withdrawn:
                    lblUpdateHistory.Visible = true;
                    btnTakeOffline.Visible = false;
                    pnlUpdate.Visible = false;

                    lblUpdateHistory.Text = string.Format("此广告已于{0:f}撤销", postToEdit.LastEditTime);
                    break;
            }
        }

        private void GetPostIdAndEditKey()
        {
            object obj1 = Request.QueryString[GlobalQueryString.EditPostIdQsName];
            object obj2 = Request.QueryString[GlobalQueryString.EditPostEditKeyQsName];

            if (obj1 == null || obj2 == null)
                return;

            if (!Int32.TryParse(obj1.ToString(), out _maskedPostId))
                return;

            _editKey = obj2.ToString();
        }

        private bool Authenticate(out ForSaleAd postToEdit)
        {
            postToEdit = null;

            GetPostIdAndEditKey();

            if (_maskedPostId <= 0 || string.IsNullOrEmpty(_editKey))
            {
                return false;
            }

            // get the real post Id
            PostId = SecurityUtility.UnmaskEditPostId(_maskedPostId);

            if (PostId <= 0)
            {
                return false;
            }

            postToEdit = _adService.GetForSaleAdByIdAndEditKey(PostId, _editKey);

            return postToEdit != null;
        }

        private void DisplayPostDetails(ForSaleAd postToEdit)
        {
            pnlLoginError.Visible = false;
            DisplayProfilePicture( postToEdit );
            DisplayAdSummary( postToEdit );
        }

        private void DisplayProfilePicture(ForSaleAd post)
        {
            if (imgProfile != null)
            {
                if (!string.IsNullOrEmpty(post.ProfilePhotoPath)) 
                {
                    string path = Path.Combine(GlobalSettings.ThumbnailFolder, Path.GetFileName(post.ProfilePhotoPath));

                    if (File.Exists(Server.MapPath(path)))
                    {
                        imgProfile.ImageUrl = path;
                        return;
                    }
                }

                // display "Photo Not Available" 
                imgProfile.ImageUrl = GlobalSettings.PhotoNotAvailablePath;
            }
        }

        // Make, Model, and year
        private void DisplayAdSummary( ForSaleAd post )
        {
            lblVehicleType.Text = post.GetVehicleTypeString();
            lblPrice.Text = string.Format("${0}", post.Price.ToString());
            lblCity.Text = post.CityName;

            lblPostDate.Text = post.TimePosted.Date.ToShortDateString();
            lblPhone.Text = post.ContactPhone;
            lblEmail.Text = post.ContactEmail;
        }

        // update price
        protected void btnUpdatePrice_Click(object sender, EventArgs e)
        {
            int newPrice = 0;
            if (_postValidator.ValidatePrice(txtUpdatePrice.Text.Trim(), out newPrice))
            {
                if (_adService.UpdatePrice(PostId, newPrice))
                {
                    lblPrice.Text = string.Format("${0}", newPrice);
                    lblUpdatePriceFeedback.Text = EditPost_aspx.UpdatePriceDone;
                    lblUpdatePriceFeedback.CssClass = "ok-message";
                }
            }
            else
            {
                // invalid price, show some message
                lblUpdatePriceFeedback.Text = EditPost_aspx.InvalidPrice;
                lblUpdatePriceFeedback.CssClass = "error-message";
            }
        }

        // take the post offline
        protected void TakeOfflineClick(object sender, EventArgs e)
        {
            try
            {
                _adService.TakePostOffline(PostId);
                lblUpdateHistory.Text = EditPost_aspx.PostHasBeenTakenOffline;
                lblUpdateHistory.CssClass = "ok-message";
            }
            catch (Exception)
            {
                lblUpdateHistory.Text = EditPost_aspx.TakeOfflineFailed;
                lblUpdateHistory.CssClass = "error-message";
            }
        }

        private void DisplayCanNotAuthenticatePage()
        {
            // hide the edit post controls
            pnlEditPost.Visible = false;
            lblLoginError.Text = "登陆错误";
        }

        protected void btnTryAgain_Click(object sender, EventArgs e)
        {
            Response.Redirect(BuildEditPostLink(_maskedPostId));
        }

        private string BuildEditPostLink(int maskedEditPostId)
        {
            if (SecurityUtility.IsValidPostId(maskedEditPostId))
            {
                return string.Format("~/EditPostForm/EditPost.aspx?{0}={1}", GlobalQueryString.EditPostIdQsName, maskedEditPostId);
            }
            else
            {
                return "~/EditPost/EditPostForm.aspx";
            }
        }
    }
}
